const App = getApp();
const db = wx.cloud.database();
const _ = db.command;
let that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 编辑更新弹窗
    setShow: false,
    // 信息列表展开
    baseShow: false,
    // 成员展开
    baseMemberShow: true,
    // 附件展开
    baseFileShow: true,
    // 附件下载弹窗
    fileDownload: "",
    // 附件详情弹窗
    fileDetails: "",
    // 附件详情内容
    fileData: "",
    // 附件添加按钮loading
    btnloading: false,
    // 成员添加按钮loading
    memberBtnLoading: false,
    // 搜索同学弹窗
    searchShow: false,
    searchValue: null,
    searchNum: 0,
    // 添加搜索到的同学
    searchMember: [],
    // 删除成员
    removeShow: false,
    // 被点击的成员的信息
    memberInfo: "",
    // 实践基地详情
    BaseData: {},
    // 下载回来的链接
    downloadFilePath: "",
    // 显示fab
    fabShow: false,
    // 笼罩层
    overlayShow: false,

    // 输入框高度
    inputHeight: {
      minHeight: 80
    },
    // 判断是开始还是结束的值
    TimeKey: "",
    // 更新集合
    setList: {
      name: "",
      location: "",
      profession: "",
      addTime: null,
      endTime: null,
      ContactPerson: "",
      ContactNumber: null,
      remark: ""
    },
    // 菜单列表
    Menulist: [{
        name: "编辑更新",
        icon: "icon-editor",
        bg: "repeating-linear-gradient(45deg, #00d1FF, #69FF97)",
        path: "",
        bindtap: "setShowPopup",
      }, {
        name: "添加附件",
        icon: "icon-shangchuan",
        bg: "repeating-linear-gradient(45deg, #ED1C24, #FECE12)",
        path: "",
        bindtap: "addfile",
      },
      {
        name: "添加成员",
        icon: "icon-B",
        bg: " repeating-linear-gradient(45deg, #24FE41, #F7FD47)",
        path: "",
        bindtap: "searchshowPopup",
      },
      {
        name: "删除实训基地",
        icon: "icon-shanchu",
        bg: "repeating-linear-gradient(45deg, #F5317F, #FF7C6E)",
        path: "",
        bindtap: "removePracticeBase",
      },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    that = this
    let data = JSON.parse(decodeURIComponent(options.passData));
    console.log('传值后', data);
    let UserInfo = App.cache.getUserInfo()
    console.log('获取用户信息:', UserInfo);
    delete UserInfo._id
    that.setData({
      UserInfo: UserInfo,
      practiceBaseId: data.practiceBaseId
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    that.getpracticeBase()
    that.getpracticeBaseFile()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 打开编辑更新弹窗
  setShowPopup() {
    this.setData({
      setShow: true
    });
  },
  // 关闭编辑更新弹窗
  setOnClose() {
    this.setData({
      setShow: false
    });
  },
  // 信息展开
  baseShow() {
    that.setData({
      baseShow: !that.data.baseShow
    })
  },
  // 附件展开
  baseFileShow() {
    that.setData({
      baseFileShow: !that.data.baseFileShow
    })
  },
  // 成员展开
  baseMemberShow() {
    that.setData({
      baseMemberShow: !that.data.baseMemberShow
    })
  },
  // 关闭下载弹窗
  hideModal(e) {
    this.setData({
      fileDownload: ""
    })
  },

  // 打开详情弹窗
  fileDetails(e) {
    let data = e.currentTarget.dataset.data
    console.log(data);
    that.setData({
      fileData: data,
      fileDetails: 'show'
    })
  },
  // 关闭详情弹窗
  CloseFileDetails(e) {
    this.setData({
      fileDetails: ""
    })
  },
  // fab
  fabShow() {
    that.setData({
      overlayShow: !that.data.overlayShow,
      fabShow: !that.data.fabShow
    });
  },
  // 关闭fab和笼罩层
  onClickHide() {
    that.setData({
      overlayShow: false,
      fabShow: false
    });
  },
  // 上传附件
  addfile() {
    // 关闭笼罩层
    that.onClickHide()
    that.setData({
      btnloading: true,
      baseFileShow: true,
    })
    wx.chooseMessageFile({
      count: 30,
      type: 'all',
      success(res) {
        console.log(res);
        let data = res.tempFiles
        console.log(data);
        const uploadTasks = data.map((file, index) => {
          let cloudPath = "实践基地附件/" + that.data.BaseData.name + '/' + file.name
          return wx.cloud.uploadFile({
            cloudPath: cloudPath,
            filePath: file.path
          });
        });
        Promise.all(uploadTasks)
          .then(res => {
            let list = []
            res.forEach((item, index) => {
              list.push({
                name: data[index].name,
                size: (data[index].size / 1024 / 1024).toFixed(2),
                id: item.fileID,
                type: data[index].type,
                timeTs: Date.now(),
                fileId: Date.now() + index
              })
            })
            console.log('list', list);
            return list
          })
          .then(file => {
            console.log('拿到上传好的文件id', file);
            // 上传数据库
            db.collection('practiceBase').where({
              practiceBaseId: that.data.practiceBaseId
            }).update({
              data: {
                file: _.push(file)
              },
              success: function (res) {
                console.log('上传成功', res);
                App.toast.showToast('上传成功')
                that.setData({
                  btnloading: false
                })
                that.getpracticeBase()
              }
            })
          })
          .catch(e => {
            that.setData({
              btnloading: false
            })
            console.log(e);
          });
      },
      fail: function (res) {
        that.setData({
          btnloading: false
        })
      }
    })
  },

  // 下载文件到本地
  downloadFile(e) {
    let fileid = e.currentTarget.dataset.fileid
    console.log('fileid', fileid);
    // 如果是打开详情再下载的，那就把详情弹窗关掉先
    that.setData({
      fileDetails: ""
    })
    App.toast.showLoading('下载中')
    wx.cloud.getTempFileURL({
      fileList: [{
        fileID: fileid,
      }]
    }).then(res => {
      App.toast.hideLoading()
      console.log('返回来的链接', res.fileList[0])
      that.setData({
        fileDownload: "show",
        downloadFilePath: res.fileList[0].tempFileURL,
      })
    }).catch(error => {
      console.error(error)
    })
  },
  // 复制文件链接地址
  codeFilePath(e) {
    console.log(e.currentTarget.dataset);
    let filepath = e.currentTarget.dataset.filepath
    wx.setClipboardData({
      data: filepath,
      success: res => {
        console.log(res);
        App.toast.showToast('链接已经复制', 'none', 1000)
        that.hideModal()
      }
    })
  },

  // 删除文件
  removerFile(e) {
    let file = e.currentTarget.dataset.file
    console.log('file', file);
    that.CloseFileDetails()
    App.toast.showLoading('删除中')
    db.collection('practiceBase').where(_.and([{
        practiceBaseId: that.data.practiceBaseId
      },
      {
        file: _.elemMatch({
          fileId: file.fileId
        })
      },
      {
        file: _.elemMatch({
          name: file.name
        })
      }
    ])).update({
      data: {
        file: _.pull({
          fileId: _.eq(file.fileId)
        })
      },
      success: function (res) {
        App.toast.hideLoading()
        console.log('删除成功', res);
        let fileList = that.data.BaseData.file
        fileList.forEach((item, index) => {
          if (item.fileId === file.fileId) {
            fileList.splice(index, 1)
          }
        })
        console.log('fileList', fileList);
        that.setData({
          ['BaseData.file']: fileList
        })
      }
    })
  },

  // 是否拨号
  dial(e) {
    console.log(e.currentTarget.dataset.number);
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.number
    })
  },

  //打开搜索同学弹窗
  searchshowPopup(e) {
    // 关闭笼罩层
    that.onClickHide()
    this.setData({
      searchShow: true,
      baseMemberShow: true,
    });
  },
  // 关闭搜索同学弹窗
  onCloseSearch() {
    this.setData({
      searchShow: false
    });
  },
  // 打开删除成员弹窗
  showPopup(e) {
    console.log(e.currentTarget.dataset.member);
    let Info = e.currentTarget.dataset.member
    console.log('有吗', Info);
    this.setData({
      removeShow: true,
      memberInfo: Info,
    });
  },
  //  关闭删除成员弹窗
  onClose() {
    this.setData({
      removeShow: false
    });
  },
  // 搜索同学
  onSearch() {
    console.log(that.data.searchValue);
    let searchValue = Number(that.data.searchValue)
    App.toast.showLoading('搜索中')
    db.collection('userInfo').where({
        account: searchValue
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log(res.data)
          that.setData({
            searchMember: res.data,
            searchNum: 1
          })
        }
      })
  },
  // 搜索输入时的变化值
  onChange(e) {
    console.log(e.detail);
    if (e.detail === '') {
      that.setData({
        searchMember: [],
        searchNum: 0
      });
    } else {
      that.setData({
        searchValue: e.detail,
      });
    }

  },
  // 打开选择时间弹窗
  TimePopup(event) {
    const {
      key
    } = event.currentTarget.dataset
    console.log('key', key);
    if (key == 'add') {
      that.setData({
        // 判断开始还是结束的值
        TimeKey: key,
      });
    } else {
      that.setData({
        // 判断开始还是结束的值
        TimeKey: key,
      });
    }
  },
  // 选择时间
  TimehandleChange(e) {
    // 获取开始时间还是结束时间
    let key = e.currentTarget.dataset.key
    // 获取标准时间
    let Time = e.detail.dateString
    // 将时间转成时间戳
    let formatTime = new Date(Time).getTime()
    if (key == 'add') {
      that.setData({
        // 判断开始还是结束的值
        TimeKey: key,
        addTime: formatTime,
        'setList.addTime': formatTime,
      });
    } else {
      that.setData({
        // 判断开始还是结束的值
        TimeKey: key,
        endTime: formatTime,
        'setList.endTime': formatTime
      });
    }
  },
  // 获取input输入的值
  handleChange(e, key) {
    const {
      detail,
      currentTarget
    } = e
    console.log('detail', detail);
    console.log('currentTarget', currentTarget);
    this.setData({
      [`setList.${currentTarget.id}`]: detail,
    })
  },

  // 获取实践基地详情
  getpracticeBase() {
    App.toast.showLoading('加载中')
    db.collection('practiceBase').where({
        practiceBaseId: that.data.practiceBaseId
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log('获取实践基地详情', res.data[0])
          let BaseData = res.data[0]
          that.setData({
            BaseData: BaseData,
            'setList.name': BaseData.name,
            'setList.location': BaseData.location,
            'setList.profession': BaseData.profession,
            'setList.addTime': BaseData.addTime,
            'setList.endTime': BaseData.endTime,
            'setList.ContactPerson': BaseData.ContactPerson,
            'setList.ContactNumber': BaseData.ContactNumber,
            'setList.remark': BaseData.remark,
          })
        }
      })
  },

  // 获取实践基地文件详情
  getpracticeBaseFile() {
    App.toast.showLoading('加载中')
    db.collection('practiceBaseFile').where({
        practiceBaseId: that.data.practiceBaseId
      })
      .get({
        success: function (res) {
          App.toast.hideLoading()
          console.log('获取实践基地文件详情', res.data)
          that.setData({
            membersList: res.data
          })
        }
      })
  },

  // 添加成员
  addMember(e) {
    let member = e.currentTarget.dataset.member
    delete member._id
    delete member.password
    console.log('member', member);
    App.toast.showLoading('添加中')
    db.collection('practiceBase').where(_.and([{
          practiceBaseId: that.data.practiceBaseId
        },
        {
          members: _.elemMatch({
            account: _.eq(member.account)
          })
        }
      ]))
      .get()
      .then(res => {
        App.toast.hideLoading()
        console.log(res.data[0])
        if (typeof (res.data[0]) == "undefined") {
          App.toast.showLoading('添加中')
          db.collection('practiceBase').where({
            practiceBaseId: that.data.practiceBaseId,
          }).update({
            data: {
              members: _.push(member)
            },
            success: function (res) {
              db.collection('practiceBaseFile').add({
                  data: {
                    Submit: false,
                    Review: false,
                    results: "",
                    practiceBaseId: that.data.practiceBaseId,
                    account: member.account,
                    avatarUrl: member.avatarUrl,
                    collegeId: member.collegeId,
                    email: member.email,
                    gender: member.gender,
                    identityId: member.identityId,
                    nickName: member.nickName,
                    permissions: member.permissions,
                    StartFile: [],
                    OngoingFile: [],
                    EndFile: []
                  }
                })
                .then(res => {
                  App.toast.hideLoading()
                  console.log('添加成功', res);
                  App.toast.showToast('添加成功')
                  that.getpracticeBaseFile()
                  that.setData({
                    searchValue: "",
                    searchMember: [],
                    searchNum: 0
                  })
                })
            }
          })
        } else {
          App.toast.showToast('该成员已在本实践基地')
          that.setData({
            searchValue: "",
            searchMember: [],
            searchNum: 0
          })
        }
      })
  },
  // 更新实践基地
  setPracticeBase() {
    let setList = that.data.setList
    console.log('setList', setList);
    App.toast.showLoading('更新中')
    db.collection('practiceBase').where({
      practiceBaseId: that.data.practiceBaseId,
    }).update({
      data: {
        name: setList.name,
        location: setList.location,
        profession: setList.profession,
        addTime: setList.addTime,
        endTime: setList.endTime,
        ContactPerson: setList.ContactPerson,
        ContactNumber: setList.ContactNumber,
        remark: setList.remark,
      },
      success: function (res) {
        App.toast.hideLoading()
        console.log('更新成功', res);
        that.setData({
          baseShow: true
        })
        that.setOnClose()
        that.onClickHide()
        App.toast.showToast('更新成功')
        that.getpracticeBase()
      }
    })
  },

  // 删除实践基地
  removePracticeBase() {
    wx.showModal({
      title: '提示',
      content: '确定删除实践基地吗',
      success(res) {
        if (res.confirm) {
          db.collection('practiceBase').doc(that.data.BaseData._id).remove({
            success: function (res) {
              console.log(res.data)
              App.route.relBack('/pages/practiceBase/list/index')
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 前往成员详情
  routeMembers(e) {
    console.log(e.currentTarget.dataset.item);
    let item = e.currentTarget.dataset.item
    let BaseData = that.data.BaseData
    if (that.data.UserInfo.account === BaseData.creator.account || that.data.permissions === true) {
      let data = {}
      data.account = item.account
      data.practiceBaseId = BaseData.practiceBaseId
      data.removeId = item._id
      console.log('data', data);
      App.route.navTo('/pages/practiceBase/details/members/index', data)
    }
  },
  // 成员前往自己的详情
  routeMembersInfo() {
    let data = {}
    data.account = that.data.UserInfo.account
    data.practiceBaseId = that.data.BaseData.practiceBaseId
    data.removeId = that.data.membersList._id
    console.log('data', data);
    App.route.navTo('/pages/practiceBase/details/members/index', data)
  }
})